package com.example.userserver.service;


import com.example.server_engineer.controller.utils.R;
import com.example.server_engineer.service.AbstractTypedService;
import com.example.userserver.dao.UserDao;
import com.example.userserver.entities.CommonResult;
import com.example.userserver.entities.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author Administrator
 */
@Slf4j
@Service
public class UserService
        extends AbstractTypedService<User, Long> {

//    @Resource
//    FileStorageService fileStorageService;

    @Resource
    UserDao userdao;

    //    构造函数注入
    UserService(UserDao dao) {
        this.dataContext = dao;
        this.userdao = dao;
    }


    // 登录
    public User login(String username, String password) {
        User user = userdao.findByUsernameAndPassword(username,password);
        System.out.println(user);
        return user;
    }

    // 注册
    public CommonResult<User> register(User u){
        User user = new User();
        // 这里的 username是手机号码，所以不能重复
        User user1 = userdao.findUserByUsername(u.getUsername());
        System.out.println(u.getUsername());
        if(user1 == null){
            user.setUsername(u.getUsername());
            user.setPassword(u.getPassword());
            user.setMobilePhone(u.getUsername());
            user.setSex(u.getSex());
            this.dataContext.save(user);
            return new CommonResult<>(200, "注册成功", user);
//            return new R(true,user);
        }
        return new CommonResult<>(400, "注册失败", null);
//        return new R(false,"用户名已存在!");

    }


//    public String setImgByUserId(String id, MultipartFile file){
//        FileInfo upload = fileStorageService.of(file).upload();
//        Integer integer = userdao.updateImgByUserId(upload.getUrl(),id);
//
//        if(integer == 0){
//            return "false";
//        }
//        return "true";
//    }

    public User getUserById(Long id) {
        if (id == null || id <= 0) {
            return null;
        }
        return userdao.findById(id).orElse(null);
    }

    /**
     * @return User
     */
    public User getUserByUserName(String userName) {

        var us = this.userdao.findUserByUsername(userName);

        return us;
    }

    public User findUserByEmail(String userName) {

        var us = this.userdao.findUserByEmail(userName);

        return us;
    }

    public User findUserByTel(String userName) {

        var us = this.userdao.findUserByTelOrMobilePhone(userName, userName);

        return us;
    }

}
